package com.dingteam.question.common.validation.module.text;

import com.dingteam.model.Result;
import com.dingteam.question.common.dto.QuestionPaperVerifyDTO;
import com.dingteam.question.common.dto.QuestionResultVerifyDTO;
import com.dingteam.question.common.enums.ModuleEnum;
import com.dingteam.question.common.enums.TextTypeEnum;
import com.dingteam.question.common.validation.module.AbstractModuleTextValidator;
import com.dingteam.validation.util.RegexUtils;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Jamin
 * @date 2019/07/08
 */
@Component
public class TextValidator extends AbstractModuleTextValidator {

	@Getter
	private final ModuleEnum module = ModuleEnum.TEXT;

	@Override
	public boolean supportModule(ModuleEnum moduleEnum) {
		return module.equals(moduleEnum);
	}

	@Override
	public Result<String> createValid(QuestionPaperVerifyDTO.QuestionItemDTO itemDTO) {
		Result<String> result = validCreateCommon(itemDTO);
		if (!result.getSuccess()) {
			return result;
		}
		if (StringUtils.isBlank(itemDTO.getTextType())) {
			return Result.error("{validation.item.textType.blank.message}", EMPTY);
		}
		if (Objects.isNull(itemDTO.getMin())) {
			return Result.error("{validation.item.min.null.message}", EMPTY);
		}
		if (Objects.isNull(itemDTO.getMax())) {
			return Result.error("{validation.item.max.null.message}", EMPTY);
		}
		if (itemDTO.getMin() > itemDTO.getMax()) {
			return Result.error("{validation.item.min.illegal.message}", EMPTY);
		}
		if (itemDTO.getMax() > MAX_VALUE) {
			return Result.error("{validation.item.max.illegal.message}", EMPTY);
		}
		return Result.ok().build();
	}

	@Override
	public Result<String> submitValid(QuestionResultVerifyDTO.ItemResultDTO item) {
		Result<String> result = validSubmitCommon(item);
		if (!result.getSuccess()) {
			return result;
		}
		String content = item.getContent();
		if (StringUtils.isNotBlank(content)) {
			TextTypeEnum textTypeEnum = TextTypeEnum.valueOfAlias(item.getQuestionItem().getTextType());
			switch (textTypeEnum) {
				case NUMBER:
					try {
						Double.valueOf(content);
					} catch (Exception e) {
						return Result.error("{validation.text.number.illegal.message}", EMPTY);
					}
					break;
				case TELEPHONE:
					if (!RegexUtils.isMobile(content)) {
						return Result.error("{validation.text.telephone.illegal.message}", EMPTY);
					}
					break;
				case EMAIL:
					if (!RegexUtils.isEmail(content)) {
						return Result.error("{validation.text.email.illegal.message}", EMPTY);
					}
					break;
				default:
					break;
			}
		}
		return Result.ok().build();
	}
}
